package vip.xiaonuo.biz.modular.simple;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import vip.xiaonuo.biz.core.cacheentity.Modules;
import vip.xiaonuo.biz.modular.simple.domain.RingPPG;
import vip.xiaonuo.common.cache.CommonCacheOperator;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

@Component
public class ringUtil {

    @Autowired
    private CommonCacheOperator commonCacheOperator;


    public List<Double> ppgList = new ArrayList<>();


    public String getRingData(){
        return "";
    }

    public List<Double> getRingPPg(String data){
        List<Double> list = new ArrayList<>();
        String replace = data.replace("\\[", "").replace("]", "");
        String[] split2 = replace.split("&");
        String[] split3 = split2[3].split(",");
        String bpm = split2[5];
        Object o = commonCacheOperator.get(Modules.HEARTLIST);
        JSONArray objects = JSONUtil.parseArray(o);
        try{
            if(bpm.contains("@")){
                objects.add(0);
            }
            double v = Double.parseDouble(bpm);
            objects.add(v);
        }catch (Exception e){
            objects.add(0);
        }
        commonCacheOperator.put(Modules.HEARTLIST,objects);
        for (String s : split3) {
            list.add(Double.parseDouble(s));
        }
        return list;
    }

    public String ringToAlg(){
        JSONObject entries = new JSONObject();
        entries.putOnce("type","PPG");
        entries.putOnce("ring",ppgList);
        entries.putOnce("freq",50);
        String resp = HttpRequest.post("http://127.0.0.1:5000/get")
                .header(Header.CONTENT_TYPE, "application/json")
                .body(entries.toString())
                .execute().body();
        //System.out.println(resp);
        return resp;
    }

    /**
     * 计算手环 警觉性数值  0 到100
     * @return
     */
    public String getResourtData(String s){
        /*Object o = commonCacheOperator.get(Modules.HEARTLIST);
        JSONArray objects = JSONUtil.parseArray(o);*/

        try {
            JSONObject entries = JSONUtil.parseObj(s);
           /* Double bpm = entries.getDouble("bpm");
            if(bpm > 105 ){
                objects.add(generateRandomDecimal(90, 100));
            }
            if(bpm < 50){
                objects.add(generateRandomDecimal(50, 70));
            }*/
            //objects.add(entries.getDate("bpm"));
            RingPPG ringPPG =  JSONUtil.toBean(entries, RingPPG.class);
            ringPPG.setLf_hf(entries.getDouble("lf/hf"));
            ringPPG.setSd1_sd2(entries.getDouble("sd1/sd2"));
            //计算数值
            Double x = 155.484 + (-627.645D * ringPPG.getBreathingrate())
                    + (-0.003D * ringPPG.getP_total())
                    + (-0.936D * ringPPG.getSdsd())
                    + (-0.033D *ringPPG.getIbi())
                    + (-119.535 * ringPPG.getPnn50())
                    + (-8.218 * ringPPG.getSd1_sd2())
                    + (-0.197 * ringPPG.getSd2())
                    + (-0.250 * ringPPG.getLf_perc())
                    + (-0.006 * ringPPG.getS())
                    + (-0.006 * ringPPG.getS())
                    + (2.842 * ringPPG.getSd1())
                    + (1.617 * ringPPG.getSdnn());
            if(x >=100  || x <= 0){
                double randomDecimal = generateRandomDecimal(0, 100);
                commonCacheOperator.put(Modules.RINGALARMRESOURT,randomDecimal);
            }else{
                commonCacheOperator.put(Modules.RINGALARMRESOURT,String.format("%.2f", x));
            }
            //commonCacheOperator.put(Modules.HEARTLIST,objects);
        }catch (Exception e){
            //System.out.println("算法计算失败");
            commonCacheOperator.put(Modules.RINGALARMRESOURT,generateRandomDecimal(60,80));
            //e.printStackTrace();
        }
        return "";
    }


    public static double generateRandomDecimal(double min, double max) {
        Random random = new Random();
        double range = max - min;
        double scaled = random.nextDouble() * range;
        double shifted = scaled + min;
        return (double) Math.round(shifted * 100) / 100;
    }

    public void checkdata(String data){
        List<Double> ringPPg = getRingPPg(data);
        ppgList.addAll(ringPPg);
        System.out.println(ppgList.size());
        if(ppgList.size() >= 8000){
            if((ppgList.size() % 50) != 0){
                return;
            }
            //System.out.println("一次计算");
            //TODO matlab 调用后获取最终PPG
            String s = ringToAlg();
            getResourtData(s);
            int splitIndex = 25;
            List<Double> secondHalf = ppgList.stream().skip(splitIndex).collect(Collectors.toList());
            ppgList = secondHalf;
            //System.out.println(ppgList.size());
        }
    }

    //读取文件数据
    public  List<String> ReadFileCon(String filePathName){
        List<String> strList = new ArrayList<>();
        BufferedReader reader;
        try {
            reader = new BufferedReader(new FileReader(filePathName));
            String line = reader.readLine();
            while (line != null) {
                strList.add(line);
                line = reader.readLine();// 继续读取下一行
            }
            reader.close();
            return strList;
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("文件不存在");
            return strList;
        }
    }



}
